<template>
  <el-dialog :title="title" :visible.sync="visibile" append-to-body width="50%" @close="handleCancel">
    <div class="table-content">
      <avue-form :option="option" v-if="type === 'detail'" v-model="detailForm">
        <template slot-scope="{ disabled, size }" slot="material">
          <avue-crud
            :option="detailTableOption"
            :table-loading="tableLoading"
            :data="materialData"
            ref="crud"
            @current-change="currentChange"
            @size-change="sizeChange"
            @tree-load="treeLoadData"
          >
          </avue-crud>
        </template>
      </avue-form>
      <el-row v-else>
        <avue-form ref="form" :option="dialogSearchOption" v-model="dialogSearchFrom">
          <template slot-scope="{ size }" slot="menuForm">
            <el-button type="primary" icon="el-icon-search" :size="size" @click="searchChange">搜索</el-button>
            <el-button :size="size" icon="el-icon-delete" @click="searchReset">清空</el-button>
          </template>
        </avue-form>
        <el-col :span="10">
          <avue-crud
            :option="materialTableOption"
            :table-loading="tableLoading"
            :data="data"
            :page.sync="page"
            ref="mainCrud"
            @selection-change="selectionChange"
            @current-change="currentChange"
            @size-change="sizeChange"
            @tree-load="treeLoadData"
          >
          </avue-crud>
        </el-col>
        <el-col :span="4">
          <div class="btn-container">
            <div class="circle" @click="handleSelectDataToLeft"><i class="el-icon-arrow-left"></i></div>
            <div class="circle" @click="handleSelectDataToRight">
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </el-col>
        <el-col :span="10">
          <avue-crud :option="templateMaterialTableOption" ref="templateCrud" @tree-load="treeLoadData" @selection-change="selectionTemplateChange" :data="templateData">
          </avue-crud>
        </el-col>
      </el-row>
    </div>
    <span slot="footer" class="dialog-footer" v-if="type !== 'detail'">
      <el-button type="primary" size="small" @click="handleConfirm">确 定</el-button>
      <el-button size="small" @click="handleCancel">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  detailOption,
  detailTableOption,
  dialogSearchOption,
  getMaterialTableOption,
  getTemplateMaterialTableOption
} from '@/views/warehouse/productrefactor/materialStorageManagement.js';
import { detail, getMaterial, getMaterialCategory } from '@/api/warehouse/materialStorageManagement';
import { getAreaTree } from '@/api/admin/storage';
import { add } from '@/api/warehouse/warehouseManagement';
import { getMenuTree } from '@/api/admin/partcategory';
export default {
  name: 'dialogForm',
  props: {
    visibile: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ''
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  watch: {
    async visibile(val) {
      if (!val) {
        return;
      }
      const materialColumn = [
        {
          label: '物料类别',
          prop: 'categoryId',
          type: 'tree',
          // dicUrl: '/api/mes-admin/part-category/tree',
          props: {
            label: 'title',
            value: 'id'
          },
          dicData: [],
          formatter: (row, value, column) => {
            return row.categoryName;
          }
        },
        {
          label: '物料',
          prop: 'name'
        }
      ];
      const categoryColumn = [
        {
          label: '物料类别',
          prop: 'name'
        }
      ];
      if (this.type === 'detail') {
        this.title = '详情';
        this.detailForm = this.rowData;
        this.materialData = this.rowData.partMasterList || [].map((item) => ({ categoryName: item.categoryName, name: item.name }));
      } else if (this.type === 'material') {
        this.title = '物料数据';
        this.$set(this.materialTableOption, 'column', materialColumn);
        this.$set(this.templateMaterialTableOption, 'column', materialColumn);
        this.$set(this.dialogSearchOption, 'column', materialColumn);
        await this.getCatagory();
        if (this.rowData.partMasters) {
          this.templateData = this.rowData.partMasterList || [];
        }
        await this.initMaterialData();
        this.$refs.mainCrud && this.$refs.mainCrud.refreshTable();
        this.$refs.templateCrud && this.$refs.templateCrud.refreshTable();
      } else if (this.type === 'detailCategory') {
        this.title = '物料类别';
        this.$set(this.materialTableOption, 'column', categoryColumn);
        this.$set(this.templateMaterialTableOption, 'column', categoryColumn);
        this.$set(this.dialogSearchOption, 'column', categoryColumn);
        if (this.rowData.partCategoryList && this.rowData.partCategoryList.length) {
          this.templateData = this.rowData.partCategoryList.map((item) => ({ id: item.id, name: item.name }));
        }
        await this.initCategoryData(this.page);
        this.$refs.mainCrud && this.$refs.mainCrud.refreshTable();
        this.$refs.templateCrud && this.$refs.templateCrud.refreshTable();
      }
      this.selectData();
    }
    // type(value) {
    //   if (value === 'detailCategory') {
    //     this.page = null;
    //   } else if (value === 'material') {
    //     this.page = {
    //       pageSize: 20,
    //       currentPage: 1,
    //       total: 1
    //     };
    //   }
    // }
  },
  data() {
    return {
      loading: false,
      tableLoading: false,
      detailForm: {},
      materialData: [],
      from: {},
      title: '详情',
      option: detailOption,
      data: [],
      localData: [], // data的副本数据 用于还原前端过滤
      templateData: [],
      detailTableOption,
      materialTableOption: getMaterialTableOption(this),
      templateMaterialTableOption: getTemplateMaterialTableOption(this),
      dialogSearchOption,
      dialogSearchFrom: {},
      selectionList: [],
      temSelectionList: [],
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 1
      }
    };
  },
  methods: {
    async initCategoryData() {
      try {
        this.tableLoading = true;
        this.data = [];
        // const res = await getMaterialCategory();
        // this.data = res.data.data;
        // this.localData = this._cloneDeep(this.data);
        const params = {
          current: this.page.currentPage,
          size: this.page.pageSize
        };
        if (this.dialogSearchFrom.name) {
          params.name = this.dialogSearchFrom.name;
        }
        const res = await getMaterialCategory(Object.assign(params, { parentId: 0 }));
        const data = res.data.data;
        this.data = data.records;
        this.page.total = data.total;
        this.page.pageSize = data.size;
        this.selectData();
      } catch (e) {
        console.warn(e);
      } finally {
        this.tableLoading = false;
      }
    },
    async initMaterialData() {
      try {
        this.tableLoading = true;
        this.data = [];
        const res = await getMaterial({ size: this.page.pageSize, current: this.page.currentPage, categoryIdsStr: this.rowData.partCategories });
        const data = res.data.data;
        this.data = data.records;
        this.page.total = data.total;
        this.page.pageSize = data.size;
      } catch (e) {
        console.warn(e);
      } finally {
        this.tableLoading = false;
      }
    },
    selectData() {
      if (this.data.length && this.templateData.length) {
        this.data.forEach((item) => {
          if (this.templateData.map((i) => i.id).includes(item.id)) {
            setTimeout(() => {
              this.$refs.mainCrud.toggleRowSelection(item, true);
            });
          }
        });
      }
    },
    //懒加载区域与储位表格树

    treeLoadData(tree, treeNode, resolve) {
      const parentId = tree.id;
      getMaterialCategory({ parentId }).then((res) => {
        let data = res.data.data.records;
        resolve(data);
      });
      resolve(tree.children);
    },
    handleCancel() {
      this.templateData = [];
      if (this.type === 'detailCategory') {
        this.data = this.localData;
      }
      this.$refs.form && this.$refs.form.resetForm();
      this.page = {
        pageSize: 20,
        currentPage: 1,
        total: 1
      };
      this.$emit('update:visibile', false);
      this.$emit('onCancel');
    },
    handleConfirm() {
      this.saveData();
    },
    async saveData() {
      try {
        const params = {
          ...this.rowData
        };
        if (this.type === 'material') {
          params.partMasterList = this.templateData;
          params.partMasters = this.templateData.map((item) => item.id).join(',');
        } else if (this.type === 'detailCategory') {
          params.partCategoryList = this.templateData;
          params.partCategories = this.templateData.map((item) => item.id).join(',');
        }
        // 这个详情接口用来存数据
        const res = await add(params);
        this.$message.success('保存成功');
        this.$emit('onConfirm', this.from);
        this.selectionList = [];
      } catch (e) {
        console.warn(e);
      } finally {
        this.tableLoading = false;
      }
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.type === 'detailCategory' ? this.initCategoryData() : this.getMarteData();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.type === 'detailCategory' ? this.initCategoryData() : this.getMarteData();
    },
    searchReset() {
      this.$refs.form.resetForm();
      this.handleSearch();
    },
    searchChange() {
      this.handleSearch();
    },
    async getMarteData() {
      try {
        this.tableLoading = true;
        const params = this.getParams();
        const res = await getMaterial(params);
        const data = res.data.data;
        this.data = data.records;
        this.page.total = data.total;
        this.page.pageSize = data.size;
        this.selectData();
      } catch (e) {
        console.warn(e);
      } finally {
        this.tableLoading = false;
      }
    },
    getParams() {
      let obj;
      const { categoryId = '', name = '' } = this.dialogSearchFrom;
      obj = {
        categoryId,
        name,
        size: this.page.pageSize,
        current: this.page.currentPage,
        categoryIdsStr: this.rowData.partCategories
      };
      return obj;
    },
    handleSearch() {
      this.page.currentPage = 1;
      if (this.type === 'detailCategory') {
        this.initCategoryData();
      } else {
        this.getMarteData();
      }
    },
    handleSelectDataToRight() {
      // this.templateData = this.selectionList;
      this.templateData = this._unionBy(this.selectionList, this.templateData, 'id');
      // this.rightSelectionList = [];
      // this.$refs.rightCrud.refreshTable();
      // this.selectionList = [];
    },
    handleSelectDataToLeft() {
      this.templateData = this.difference(this.templateData, this.temSelectionList);
      // this.selectionList = [];
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionTemplateChange(list) {
      this.temSelectionList = list;
    },
    difference(parentSet, childSet) {
      // 使用 Set 数据结构来存储数组元素，以便进行快速查找
      const parent = new Set(parentSet);
      const child = new Set(childSet);
      // 使用 Array.from 将 Set 转换回数组
      return Array.from(new Set([...parent].filter((x) => !child.has(x))));
    },
    async getCatagory() {
      try {
        const res = await getMenuTree(1, 10000);
        const data = res.data.data;
        const column = this.findObject(this.materialTableOption.column, 'categoryId');
        column.dicData = res.data.data;
      } catch (e) {
        console.warn(e);
      }
    }
  }
};
</script>

<style scoped lang="scss">
.btn-container {
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;
  flex-wrap: nowrap;
  align-items: center;

  .circle {
    width: 40px;
    height: 40px;
    line-height: 40px;
    font-size: 20px;
    text-align: center;
    border-radius: 50%;
    margin: 10px;
    border: 1px solid #606266;
    &:hover {
      cursor: pointer;
      color: #0a84ff;
      border: 1px solid #0a84ff;
    }
  }
}

.table-content {
  height: 500px;
  ::v-deep .avue-crud__menu {
    display: none;
  }
  .dialog-footer {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 50px;
  }

  ::v-deep .el-pagination__jump {
    display: none;
  }
}

::v-deep .avue-crud__pagination {
  position: absolute;
}
</style>
